#!/bin/sh
## A script to set up reverse ssh to server and be run with cron_key.sh

# Run in crontab with:
# */10 * * * * /home/demure/projects/personal/scripts/reverse_ssh.sh

PORT="2001"
SERVER="demu.red"
CON_PORT="500"
## Set command as a var to save time
SSH_COMMAND="ssh -F /dev/null -p ${CON_PORT} -f -N -R ${PORT}:localhost:22 ${SERVER} -q"

## Check how many ssh sessions are running on the port
CHECK="$(pgrep -f "${SSH_COMMAND}" | wc -l)"

## If no sessions, start one; if more than one, kill them and start a new one.
if [ "${CHECK}" -eq "0" ]; then
    ${SSH_COMMAND}
  else
    if [ "${CHECK}" -gt "1" ]; then
        pkill -f "${SSH_COMMAND}"
        ${SSH_COMMAND}
    fi
fi
